package com.zebraphp.devtool.httpUtils.NetOkHttp.responseHandler;

import com.zebraphp.devtool.httpUtils.NetOkHttp.IOkHttp;
import com.zebraphp.devtool.util.ILog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;

import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * json类型的回调接口
 */
public abstract class JsonParseHandler implements BaseHandler {

    @Override
    public final void onOk(final Response response) {
        ResponseBody responseBody = response.body();
        String responseBodyStr = "";

        try {
            responseBodyStr = responseBody.string();
        } catch (IOException e) {
            e.printStackTrace();
            IOkHttp.mHandlerQueue.post(new Runnable() {
                @Override
                public void run() {
                    onError(response.code(), "fail read response body");
                }
            });
            return;
        } finally {
            responseBody.close();
        }

        final String finalResponseBodyStr = responseBodyStr;

        try {
            final Object result = new JSONTokener(finalResponseBodyStr).nextValue();
            if(result instanceof JSONObject) {
                IOkHttp.mHandlerQueue.post(new Runnable() {
                    @Override
                    public void run() {
                        onOkParse(response.code(), (JSONObject) result);
                    }
                });
            } else if(result instanceof JSONArray) {
                IOkHttp.mHandlerQueue.post(new Runnable() {
                    @Override
                    public void run() {
                        onOkParse(response.code(), (JSONArray) result);
                    }
                });
            } else {
                ILog.printLib("onResponse fail parse jsonobject, body=" + finalResponseBodyStr);
                IOkHttp.mHandlerQueue.post(new Runnable() {
                    @Override
                    public void run() {
                        onError(response.code(), "jsonobject 解析失败, body=" + finalResponseBodyStr);
                    }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
            IOkHttp.mHandlerQueue.post(new Runnable() {
                @Override
                public void run() {
                    onError(response.code(), "jsonobject 解析失败, body=" + finalResponseBodyStr);
                }
            });
        }
    }

    //抽象 解析参数 二次解析 容错处理
    private void onOkParse(int statusCode, JSONObject response) {
        ILog.printLib("onSuccess(int statusCode, JSONObject response) was not overriden, but callback was received");
    }

    //抽象 解析参数 二次解析 容错处理
    private void onOkParse(int statusCode, JSONArray response) {
        ILog.printLib("onSuccess(int statusCode, JSONArray response) was not overriden, but callback was received");
    }

}